package com.zsck.pos.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.ums.AppHelper;
import com.ums.anypay.service.IOnTransEndListener;
import com.chinaums.commoncheck.R;
import com.zsck.pos.base.BaseTitleActivity;
import com.zsck.pos.bean.FeeListBean;
import com.zsck.pos.bean.FeeVOListBean;
import com.zsck.pos.bean.PayData;
import com.zsck.pos.bean.PaySuccess;
import com.zsck.pos.bean.PosResult;
import com.zsck.pos.bean.TransData;
import com.zsck.pos.common.Constants;
import com.zsck.pos.net.MyObserver;
import com.zsck.pos.net.RetrofitCilent;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

public class PayActivity extends BaseTitleActivity {

    /*去支付*/
    @BindView(R.id.tv_confirm)
    TextView mTvSure;
    /*金额*/
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    /*支付类型*/
    @BindView(R.id.rg_pay_type)
    RadioGroup mRgPayType;

    private List<String> mBillIdList;

    private double mAmount = 0.0d;

    private String transAppName = "";
    private String transAppId = "";

    private List<FeeListBean> feeList;
    private String mPayer;

    private String extOrderNo;
    private List<FeeVOListBean> multiFeeList;
    private String projectId;


    @Override
    public int setLayout() {
        return R.layout.activity_pay;
    }

    @Override
    public String setTitle() {
        return "收款金额";
    }

    @Override
    public Activity setActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initEvents();
        initData();
    }


    private void initEvents() {
        mTvSure.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent.getSerializableExtra("feeList") != null) {
            Object object = intent.getSerializableExtra("feeList");
            if (object instanceof List) {
                feeList = (List<FeeListBean>) object;
            }

        }

        if (intent.getSerializableExtra("multiFeeList") != null) {
            multiFeeList = (List<FeeVOListBean>) intent.getSerializableExtra("multiFeeList");
        }

        Object object1 = intent.getSerializableExtra("billIdList");


        if (object1 instanceof List) {
            mBillIdList = (List<String>) object1;
        }
        mPayer = intent.getStringExtra("payer");
        mAmount = intent.getDoubleExtra("amount", 0.0d);
        mTvMoney.setText("" + mAmount);

        projectId = intent.getStringExtra("projectId");
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_confirm:
                initiatePosPayment();
                break;
            case R.id.btn_records:

                break;
        }
    }


    private void startCallTrans(PayData result) {
        if (result == null) {
            LogUtil.i("PayActivity", "result is null");
            return;
        }
        JSONObject transData = new JSONObject();
        try {
            extOrderNo = result.getExtOrderNo();
            BigDecimal bigDecimal = new BigDecimal(Double.toString(mAmount));
            BigDecimal bigInterestRate = new BigDecimal("100");
            BigDecimal multiply = bigDecimal.multiply(bigInterestRate);
            if (Double.toString(mAmount).equals(multiply)) {
                Toast.makeText(PayActivity.this, "请返回当前页面重新进入", Toast.LENGTH_SHORT).show();
                return;
            }
            if (bigDecimal != null && bigInterestRate != null) {
                if (multiply.compareTo(bigDecimal) == 1) {
                    transData.put("amt", multiply);//金额
                    transData.put("appId", Constants.APPID);//appId
                    transData.put("isShowResult", false);//appId
                    transData.put("extOrderNo", result.getExtOrderNo());//extOrderNo
                    transData.put("isNeedPrintReceipt", false);//交易完是否自动打印签购单，注意true表示不自动打单，false表示自动打单。若选择打单则将按照银商标准签购单样式打印，若选择不自动打单则可根据支付结果自行调用打印接口打印，请参考SDK脚本打印范例程序。
                    AppHelper.callTrans(this, transAppName, transAppId, transData, listener);
                    LogUtil.e("PAY ：", "" + multiply);
                }
            }

        } catch (JSONException e) {
            LogUtil.e("PayAct", e.getMessage());
        }
        //所有的支付应用都通过callTrans调起

    }

    private void initiatePosPayment() {
        int chechked = mRgPayType.getCheckedRadioButtonId();
        if (chechked == R.id.pay_type_card) {
            transAppName = "银行卡收款";
            transAppId = "消费";
        } else if (chechked == R.id.pay_type_alipay) {
            transAppName = "POS 通";
            transAppId = "扫一扫";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("amt", mAmount);
        map.put("appName", transAppName);
        map.put("billIdList", mBillIdList);
        map.put("projectId", projectId);
        if (multiFeeList == null) {
            map.put("feeList", feeList);
        } else {
            map.put("feeList", multiFeeList);
        }

        MyObserver<PayData> observer = new MyObserver<PayData>(this) {
            @Override
            public void onSuccess(PayData result) {
                startCallTrans(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", errorMsg);
                Toast.makeText(PayActivity.this, errorMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void reRequest() {
                initiatePosPayment();
            }
        };
        RetrofitCilent.getApiService().initiatePosPayment(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    /**
     * 支付成功回调
     *
     * @param result
     */
    private void posPayCallback(PosResult result) {
        Map<String, Object> map = new HashMap<>();
        map.put("appName", transAppName);
        if (multiFeeList == null) {
            map.put("feeList", feeList);

        } else {
            map.put("feeList", multiFeeList);

        }
//        map.put("feeList", feeList);
        map.put("amt", mAmount);
//        map.put("amt", mAmount);
        map.put("resultCode", result.getResultCode());
        map.put("billIdList", mBillIdList);
        map.put("resultMsg", result.getResultMsg());
        map.put("transData", new Gson().toJson(result.getTransData()));
        map.put("transId", transAppId);
        map.put("payer", mPayer);
        map.put("extOrderNo", extOrderNo);

        MyObserver<PaySuccess> observer = new MyObserver<PaySuccess>(this) {
            @Override
            public void onSuccess(PaySuccess result) {

                Intent intent = new Intent();
                ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.SuccessActivity");
                if (multiFeeList == null) {
                    intent.putExtra("feeList", "1");
                } else {
                    intent.putExtra("feeList", "2");
                }
                intent.setComponent(componentName);
                intent.putExtra("payData", result);
                startActivity(intent);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", errorMsg);
                Toast.makeText(PayActivity.this, errorMsg, Toast.LENGTH_LONG).show();


            }

            @Override
            public void reRequest() {
                posPayCallback(result);
            }
        };
        RetrofitCilent.getApiService().posPayCallback(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    /**
     * 支付接口调用结果监听
     **/
    IOnTransEndListener listener = new IOnTransEndListener() {
        @Override
        public void onEnd(String reslutmsg) {//reslutmsg接口调用结果

            PosResult result = new Gson().fromJson(reslutmsg, PosResult.class);
            if (result == null) {
                LogUtil.i("PayActivity", "出错了");
                return;
            }
            TransData transData = result.getTransData();
            if (transData == null) {
                LogUtil.i("PayActivity", "出错了");
                return;
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    posPayCallback(result);
                }
            });


            if (!"00".equals(transData.getResCode())) {
                Intent intent = new Intent();
                ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.ErrorActivity");
                intent.setComponent(componentName);
                startActivityForResult(intent, 0x11);
            }

        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK) {
            initiatePosPayment();
        }
    }


}
